package com.willian.andrappfw.utils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;

public class FormatUtils {
    public FormatUtils() {
    }

    public static String mapToString(Map<?, ?> map) {
        if (map.isEmpty()) {
            return "{}";
        } else {
            StringBuilder buffer = new StringBuilder();
            buffer.append('{');
            Iterator it = map.entrySet().iterator();

            while(it.hasNext()) {
                Map.Entry<?, ?> entry = (Map.Entry)it.next();
                Object key = entry.getKey();
                buffer.append(key);
                buffer.append(':');
                Object value = entry.getValue();
                buffer.append(value);
                if (it.hasNext()) {
                    buffer.append(",");
                }
            }

            buffer.append('}');
            return buffer.toString();
        }
    }

    public static String getReadableString(String str) {
        int level = 0;
        StringBuilder jsonForMatStr = new StringBuilder();

        for(int i = 0; i < str.length(); ++i) {
            char c = str.charAt(i);
            if (level > 0 && '\n' == jsonForMatStr.charAt(jsonForMatStr.length() - 1)) {
                jsonForMatStr.append(getLevelStr(level));
            }

            switch(c) {
                case ',':
                    jsonForMatStr.append(c).append("\n");
                    break;
                case '[':
                case '{':
                    jsonForMatStr.append(c).append("\n");
                    ++level;
                    break;
                case ']':
                case '}':
                    jsonForMatStr.append("\n");
                    --level;
                    if (level < 0) {
                        level = 0;
                    }

                    jsonForMatStr.append(getLevelStr(level));
                    jsonForMatStr.append(c);
                    break;
                default:
                    jsonForMatStr.append(c);
            }
        }

        return jsonForMatStr.toString();
    }

    private static String getLevelStr(int level) {
        StringBuilder levelStr = new StringBuilder();

        for(int levelI = 0; levelI < level; ++levelI) {
            levelStr.append("\t");
        }

        return levelStr.toString();
    }

    public static String getTimeString() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.CHINA);
        return sdf.format(new Date());
    }
}
